/*
 * 全局DOM尺寸监听
 *
 */
import { defineStore } from 'pinia'

const events = new Map()

const observer = new ResizeObserver(entries => {
    for (let entry of entries.reverse()) {
        const cb = events.get(entry.target.id)
        if (cb) {
            cb(entry)
        }
    }
})

export const useResizeObserverStore = defineStore('resizeObserverStore', {
    state: () => ({
        observer: observer,
        events: events
    }),
    actions: {
        createObserver(el: Element | Element[], cb: (ResizeObserverEntry: ResizeObserverEntry) => unknown) {
            const list = Array.isArray(el) ? el : [el]
            list.forEach(item => {
                this.events.set(item.id, cb),
                this.observer.observe(item)
            })
        },
        destroyObserver(el: Element) {
            this.observer.unobserve(el)
        },
        clearObserver() {
            this.observer.disconnect()
        }
    }
})
